package com.wendy.admin.controller;

import com.wendy.admin.domain.bo.SysDeptBo;
import com.wendy.admin.domain.vo.SysDeptVo;
import com.wendy.admin.entity.SysDept;
import com.wendy.admin.service.ISysDeptService;
import com.wendy.common.core.constant.UserConstants;
import com.wendy.common.core.errcode.dept.DeptError;
import com.wendy.common.core.utils.StringUtils;
import com.wendy.common.log.annotation.Log;
import com.wendy.common.log.enums.BusinessType;
import com.wendy.common.web.controller.BaseController;
import com.wendy.custom.security.annotation.RequiresPermissions;
import com.wendy.custom.security.utils.SecurityUtils;
import com.wendy.utils.spring.MapstructUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门信息
 *
 * @author wendy
 */
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController {
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/list")
    public List<SysDeptVo> list(SysDeptBo dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return MapstructUtils.convert(depts, SysDeptVo.class);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public List<SysDeptVo> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDeptBo());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return MapstructUtils.convert(depts, SysDeptVo.class);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @RequiresPermissions("system:dept:query")
    @GetMapping(value = "/{deptId}")
    public SysDeptVo getInfo(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return MapstructUtils.convert(deptService.selectDeptById(deptId),SysDeptVo.class);
    }

    /**
     * 新增部门
     */
    @RequiresPermissions("system:dept:add")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public int add(@Validated @RequestBody SysDeptBo dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            DeptError.ADD_ERROR.formatFire(dept.getDeptName());
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        SysDept addDept = MapstructUtils.convert(dept, SysDept.class);
        return deptService.insertDept(addDept);
    }

    /**
     * 修改部门
     */
    @RequiresPermissions("system:dept:edit")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public int edit(@Validated @RequestBody SysDeptBo dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept)) {
            DeptError.EDIT_ERROR.formatFire(dept.getDeptName());
        } else if (dept.getParentId().equals(deptId)) {
            DeptError.EDIT_SELF_ERROR.formatFire(dept.getDeptName());
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            DeptError.EDIT_SUB_DEPT_ERROR.fire();
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        SysDept insDept = MapstructUtils.convert(dept, SysDept.class);
        return deptService.updateDept(insDept);
    }

    /**
     * 删除部门
     */
    @RequiresPermissions("system:dept:remove")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public int remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            DeptError.DEL_SUB_DEPT_ERROR.fire();
        }
        if (deptService.checkDeptExistUser(deptId)) {
            DeptError.DEL_SUB_USER_ERROR.fire();
        }
        deptService.checkDeptDataScope(deptId);
        return deptService.deleteDeptById(deptId);
    }
}
